import 'dart:convert';
import 'dart:developer';
import 'dart:math' as math;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/match/detail/lq_match_lineup_logic.dart';
import 'package:ball_lion/entity/match/detail/lq_lineup_entity.dart';
import 'package:ball_lion/entity/match/detail/lq_match_detail_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/ladder_tab_bar.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/ads_label.dart';

class LqLineupWidget extends StatefulWidget {
  const LqLineupWidget({super.key, this.matchId});

  final int? matchId;

  @override
  State<LqLineupWidget> createState() => _LqLineupWidgetState();
}

class _LqLineupWidgetState extends State<LqLineupWidget> {
  late final LqLineupLogic logic;

  @override
  void initState() {
    logic = Get.put(LqLineupLogic(), tag: '${widget.matchId}');
    logic.matchId = widget.matchId;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqLineupLogic>(
        tag: '${widget.matchId}',
        builder: (logic) {
          return LoadingWidget<bool>(
            isLoading: logic.isLoading,
            data: List.generate(3, (index) => logic.keyScore(index)).every(
                    (element) => element.every((element) => element == 0)) &&
                logic.data.every((element) =>
                    element.every((element) => element.toJson().isEmpty)) &&
                logic.suspend.every((element) => element.isEmpty),
            child: () => EasyRefresh.builder(
              onRefresh: logic.getRefresh,
              controller: EasyRefreshController(),
              childBuilder: (context, physics) => ListView(
                physics: physics,
                children: [
                  const AdsLabel(
                    adsTag: "match_lq_统计",
                    tapType: 'ggw_bsxq_tj',
                    margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
                  ),
                  Container(height: 8),
                  LoadingWidget<int>(
                      isLoading: logic.isLoading,
                      data: logic.trends?.appMatchTrends?.length,
                      noData: Container(),
                      child: () => chartBox()),
                  LoadingWidget<int>(
                      isLoading: logic.isLoading,
                      data: logic.trends?.appMatchTrends?.length,
                      noData: Container(),
                      child: () => score1234()),
                  LoadingWidget<int>(
                      isLoading: logic.isLoading,
                      data: logic.trends?.appMatchItems?.length,
                      noData: Container(),
                      child: () => techBox()),
                  LoadingWidget<bool>(
                      isLoading: logic.isLoading,
                      data: logic.key?.awayPlayerInfo == null ||
                          logic.key?.homePlayerInfo == null,
                      noData: Container(),
                      child: () => keyData()),
                  LoadingWidget<bool>(
                      isLoading: logic.isLoading,
                      data: logic.data.every((element) =>
                          element.every((element) => element.toJson().isEmpty)),
                      noData: Container(),
                      child: () => tech()),
                  LoadingWidget<bool>(
                      isLoading: logic.isLoading,
                      data: logic.suspend.every((element) => element.isEmpty),
                      noData: Container(),
                      child: () => suspend()),
                  Container(height: 50)
                ],
              ),
            ),
          );
        });
  }

  Widget keyData() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: Colours.white,
      ),
      margin: const EdgeInsets.only(bottom: 10, left: 8, right: 8),
      padding: const EdgeInsets.only(top: 16, left: 12, right: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Image.asset(width: 24, Utils.getImgPath("match_stat_best.png")),
              Container(width: 2),
              const QsText("各项最佳", fontSize: 16, fontWeight: FontWeight.w500),
            ],
          ),
          Container(height: 16),
          Column(
              children: List.generate(
                  3,
                  (index) => confrontMap(logic.keyData(index),
                      logic.keyScore(index), logic.keyDataType(index))))
        ],
      ),
    );
  }

  Widget confrontMap(List<KeyDataInfo?> entity, List<int> score, String title) {
    return score[0] == 0 || entity[1]?.playerId == 0
        ? Container()
        : Padding(
            padding: const EdgeInsets.only(bottom: 16),
            child: Row(
              children: [
                Expanded(
                  flex: 1,
                  child: Column(
                    children: [
                      CachedNetworkImage(
                        width: 30,
                        height: 40,
                        fit: BoxFit.fitHeight,
                        imageUrl: entity[0]?.logo ?? "",
                        errorWidget: (context, url, error) =>
                            Image.asset(Utils.getImgPath("lq_placeholder.png")),
                        placeholder: (context, url) => Styles.placeholderIcon(),
                      ),
                      Container(height: 2),
                      QsText(entity[0]?.playerName ?? "", fontSize: 12),
                    ],
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          QsText("${score[0]}",
                              fontSize: 20,
                              fontFamily: "Din",
                              fontWeight: FontWeight.w600,
                              color: score[0] >= score[1]
                                  ? Colours.text
                                  : Colours.grey66),
                          QsText(title, color: Colours.grey66, fontSize: 12),
                          QsText("${score[1]}",
                              fontSize: 20,
                              fontFamily: "Din",
                              fontWeight: FontWeight.w600,
                              color: score[0] <= score[1]
                                  ? Colours.text
                                  : Colours.grey66)
                        ],
                      ),
                      Container(height: 9),
                      LayoutBuilder(builder: (context, cons) {
                        return Container(
                            width: cons.maxWidth,
                            height: 6,
                            clipBehavior: Clip.antiAlias,
                            decoration: BoxDecoration(
                                color: Colours.blue2766D6,
                                borderRadius: BorderRadius.circular(2)),
                            child: Align(
                              alignment: Alignment.centerLeft,
                              child: Container(
                                  height: 6,
                                  width: cons.maxWidth *
                                      (int.parse("${score[0]}") /
                                          (int.parse("${score[0]}") +
                                              int.parse("${score[1]}"))),
                                  color: Colours.main),
                            ));
                      })
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Column(
                    children: [
                      CachedNetworkImage(
                        width: 30,
                        height: 40,
                        fit: BoxFit.fitHeight,
                        imageUrl: entity[1]?.logo ?? "",
                        errorWidget: (context, url, error) =>
                            Image.asset(Utils.getImgPath("lq_placeholder.png")),
                        placeholder: (context, url) => Styles.placeholderIcon(),
                      ),
                      Container(height: 2),
                      QsText(entity[1]?.playerName ?? "", fontSize: 12),
                    ],
                  ),
                )
              ],
            ),
          );
  }

  Widget tech() {
    return Container(
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: Colours.white,
      ),
      margin: const EdgeInsets.only(bottom: 10, left: 8, right: 8),
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(width: 12),
              Image.asset(width: 24, Utils.getImgPath("match_stat_tech.png")),
              Container(width: 2),
              QsText("技术统计", fontSize: 16, fontWeight: FontWeight.w500),
            ],
          ),
          Column(
              children: List.generate(
                  2, (index) => lineupList(logic.data[index], index))),
          Container(
            height: 50,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Image.asset(
                    width: 16, height: 16, Utils.getImgPath("lq_shirt.png")),
                Container(width: 6),
                QsText("首发", fontSize: 12),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(width: 16),
                    Image.asset(
                        fit: BoxFit.cover,
                        width: 16,
                        height: 16,
                        Utils.getImgPath("lq_in_game.png")),
                    Container(width: 6),
                    QsText("在场", fontSize: 12)
                  ],
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget lineup() {
    return Column(
      children: [
        LadderTabBar(
          tabs: [
            QsText(logic.detail.detail?.awayTeamName ?? ""),
            QsText(logic.detail.detail?.homeTeamName ?? "")
          ],
          selectLabelStyle: TabStyle(color: Colours.main),
          onTap: (value) {
            logic.currentTab = value;
            logic.tabController
                .animateTo(value, duration: const Duration(milliseconds: 500));
          },
        ),
        SizedBox(
          height: 36 * (logic.data[logic.currentTab].length) + 30,
          child: TabBarView(
              physics: const NeverScrollableScrollPhysics(),
              controller: logic.tabController,
              children: List.generate(
                  2, (index) => lineupList(logic.data[index], index))),
        ),
        Container(
          color: Colours.white,
          height: 36,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(
                  width: 16, height: 16, Utils.getImgPath("lq_shirt.png")),
              Container(width: 6),
              QsText("首发", fontSize: 12),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(width: 16),
                  Image.asset(
                      fit: BoxFit.cover,
                      width: 16,
                      height: 16,
                      Utils.getImgPath("lq_placeholder.png")),
                  Container(width: 6),
                  QsText("在场", fontSize: 12)
                ],
              )
            ],
          ),
        )
      ],
    );
  }

  Widget lineupList(List<BbLineupDataEntity> list, int index) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.only(top: 16, bottom: 6, left: 12),
          child: Row(
            children: [
              CachedNetworkImage(
                  width: 20,
                  height: 20,
                  errorWidget: (
                    context,
                    url,
                    error,
                  ) =>
                      Image.asset(Utils.getImgPath("basket_team_logo.png")),
                  placeholder: (context, url) => Styles.placeholderIcon(),
                  imageUrl: index == 1
                      ? "${logic.detail.detail?.homeTeamLogo}"
                      : "${logic.detail.detail?.awayTeamLogo}"),
              Container(width: 5),
              QsText(
                  index == 1
                      ? (logic.detail.detail?.homeTeamName ?? "")
                      : logic.detail.detail?.awayTeamName ?? "",
                  fontWeight: FontWeight.w500)
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                      width: 12 * 7 + 3 + 16 + 16 + 6,
                      height: 30,
                      constraints: const BoxConstraints(maxHeight: 30),
                      decoration: const BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  color: Colours.greyEE, width: 0.5))),
                      alignment: Alignment.centerLeft,
                      child: QsText("球员", fontSize: 12)),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: List.generate(list.length,
                        (index) => lineupPlayerList(list[index], index)),
                  ),
                ],
              ),
              Expanded(
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  physics: const ClampingScrollPhysics(),
                  child: Column(
                    children: [
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: List.generate(
                              logic.dataType.length,
                              (index) => Container(
                                  width: 40,
                                  height: 30,
                                  constraints:
                                      const BoxConstraints(maxHeight: 30),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      border: Border(
                                          bottom: BorderSide(
                                              color: Colours.greyEE,
                                              width: 0.5))),
                                  child: QsText(logic.dataType[index],
                                      fontSize: 12)))),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: List.generate(list.length,
                            (index) => lineupDataList(list[index], index)),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget lineupPlayerList(BbLineupDataEntity entity, int index) {
    return Container(
      height: 36,
      constraints: const BoxConstraints(maxHeight: 36),
      decoration: const BoxDecoration(
          border:
              Border(bottom: BorderSide(color: Colours.greyEE, width: 0.5))),
      child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: 16,
              height: 16,
              child: Stack(
                fit: StackFit.expand,
                children: [
                  entity.first == 0
                      ? Image.asset(Utils.getImgPath("lq_shirt.png"))
                      : Image.asset(Utils.getImgPath("lq_shirt_grey.png")),
                  Center(
                      child: Padding(
                    padding: const EdgeInsets.only(top: 2),
                    child: QsText(entity.shirtNumber.toString(),
                        fontSize: 10,
                        color:
                            entity.first == 0 ? Colors.white : Colours.grey66),
                  ))
                ],
              ),
            ),
            const SizedBox(width: 6),
            ConstrainedBox(
              constraints:
                  const BoxConstraints(maxWidth: 12 * 7, minWidth: 12 * 7),
              child: QsText(
                entity.playerName ?? "",
                maxLines: 1,
                fontSize: 12,
                height: 1.4,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(width: 3),
            entity.played == 0
                ? Image.asset(
                    width: 16, height: 16, Utils.getImgPath("lq_in_game.png"))
                : Container(width: 16)
          ]),
    );
  }

  Widget lineupDataList(BbLineupDataEntity entity, int index) {
    return Container(
      constraints: const BoxConstraints(maxHeight: 36),
      decoration: const BoxDecoration(
          border:
              Border(bottom: BorderSide(color: Colours.greyEE, width: 0.5))),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: List.generate(
            logic.dataType.length,
            (childIndex) => Container(
                width: 40,
                height: 36,
                alignment: Alignment.center,
                child: QsText(logic.lineupData(entity)[childIndex],
                    fontSize: 12))),
      ),
    );
  }

  Widget suspend() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: Colours.white,
      ),
      margin: const EdgeInsets.symmetric(horizontal: 8),
      padding: const EdgeInsets.only(bottom: 10, top: 16),
      child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(width: 12),
                Image.asset(
                    width: 24, Utils.getImgPath("match_info_suspend.png")),
                Container(width: 2),
                QsText('伤病及禁赛球员', fontSize: 16, fontWeight: FontWeight.w500),
              ],
            ),
            const SizedBox(height: 10),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: List.generate(
                  2,
                  (index) => Flexible(
                      child: suspendList(logic.suspend[index], index == 1))),
            ),
          ]),
    );
  }

  Widget suspendList(List<TeamInfo> entity, bool isHome) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
          child: Row(
            children: [
              CachedNetworkImage(
                  width: 26,
                  height: 26,
                  errorWidget: (
                    context,
                    url,
                    error,
                  ) =>
                      Image.asset(Utils.getImgPath("lq_placeholder.png")),
                  placeholder: (context, url) => Styles.placeholderIcon(),
                  imageUrl: isHome
                      ? "${logic.detail.detail?.homeTeamLogo}"
                      : "${logic.detail.detail?.awayTeamLogo}"),
              Container(width: 11),
              QsText(
                  isHome
                      ? (logic.detail.detail?.homeTeamName ?? "")
                      : logic.detail.detail?.awayTeamName ?? "",
                  fontSize: 14)
            ],
          ),
        ),
        LoadingWidget<int>(
          isLoading: false,
          data: entity.length,
          noData: Container(
            alignment: Alignment.topCenter,
            padding: const EdgeInsets.symmetric(vertical: 18),
            child: QsText('暂无数据', fontSize: 11, color: Colours.grey99),
          ),
          child: () => Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              children: List.generate(entity.length,
                  (index) => suspendPlayer(isHome, entity[index])),
            ),
          ),
        ),
      ],
    );
  }

  Widget suspendPlayer(bool isHome, TeamInfo player) {
    var reasonImage = '';
    if (player.type == 2 || player.type == 3) {
      reasonImage = 'icon_jinsai.png';
    } else if (player.type == 1) {
      reasonImage = 'icon_shangbing.png';
    }
    return Container(
      width: Get.width,
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(mainAxisSize: MainAxisSize.min, children: [
        SizedBox(
          width: 24,
          height: 24,
          child: Stack(
            fit: StackFit.expand,
            children: [
              Positioned(
                child: Image.asset(
                    fit: BoxFit.fitWidth,
                    // color:
                    //     isHome ? Colours.homeColorRed : Colours.guestColorBlue,
                    Utils.getImgPath("lq_shirt.png")),
              ),
              Center(
                  child: Padding(
                padding: const EdgeInsets.only(top: 2),
                child: QsText(player.shirtNumber.toString(),
                    fontSize: 13, color: Colors.white),
              ))
            ],
          ),
        ),
        const SizedBox(width: 11),
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: QsText(
                      (player.playerName) ?? '',
                      maxLines: 1,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(width: 4),
                  if (reasonImage.isNotEmpty)
                    Image.asset(
                      Utils.getImgPath(reasonImage),
                      width: 12,
                    )
                ],
              ),
              QsText(
                  '${Utils.bbPositionName(player.position)} ${player.reason ?? ''}',
                  fontSize: 11,
                  color: Colours.grey99),
            ],
          ),
        )
      ]),
    );
  }

  Widget chartBox() {
    return Container(
      height: 192,
      margin: const EdgeInsets.only(left: 8, right: 8, bottom: 10),
      padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(8)),
      child: Column(
        children: [
          Row(
            children: [
              Image.asset(width: 24, Utils.getImgPath("match_stat_map.png")),
              Container(width: 2),
              Container(
                height: 55,
                alignment: Alignment.centerLeft,
                child:
                    QsText("分差走势", fontSize: 15, fontWeight: FontWeight.w500),
              ),
            ],
          ),
          Expanded(
            child: Row(
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    CachedNetworkImage(
                        width: 24,
                        height: 24,
                        imageUrl: logic.detail.detail?.awayTeamLogo ?? "",
                        placeholder: (context, url) => Styles.placeholderIcon(),
                        errorWidget: (context, url, error) => Image.asset(
                            Utils.getImgPath('lq_placeholder.png'))),
                    CachedNetworkImage(
                        width: 24,
                        height: 24,
                        imageUrl: logic.detail.detail?.homeTeamLogo ?? "",
                        placeholder: (context, url) => Styles.placeholderIcon(),
                        errorWidget: (context, url, error) => Image.asset(
                            Utils.getImgPath('lq_placeholder.png'))),
                    const SizedBox(height: 10)
                  ],
                ).sized(width: 30),
                Expanded(child: chart())
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget chart() {
    // 分钟
    int perTime = (logic.trends?.appMatchTrends?.isEmpty ?? true)
        ? 0
        : (logic.trends?.appMatchTrends!.first.per ?? 0);
    // 比赛节数
    int matchCount = logic.trends?.periodCount ?? 0;
    final chartsdata = chartsData();
    double max = 0;
    for (var element in chartsdata) {
      final abs = element.y.abs();
      if (abs > max) {
        max = abs;
      }
    }
    double maxX = perTime * matchCount.toDouble();
    final chart = LineChart(LineChartData(
        maxY: max,
        minY: -max,
        borderData: FlBorderData(show: false),
        minX: 0,
        maxX: maxX,
        gridData: FlGridData(
          drawVerticalLine: false,
          horizontalInterval: 11.45,
          getDrawingHorizontalLine: (value) =>
              const FlLine(color: Colours.greyD7, strokeWidth: 0.5),
        ),
        lineTouchData: LineTouchData(
            enabled: true,
            touchTooltipData: LineTouchTooltipData(
                getTooltipColor: (LineBarSpot touchedSpot) => Colors.white)),
        lineBarsData: [
          LineChartBarData(
              gradient: LinearGradient(colors: [
                Colours.blue2766D6.withOpacity(0.5),
                Colours.blue06F0FF.withOpacity(0.5)
              ]),
              spots: chartsdata,
              isCurved: false,
              barWidth: 1,
              isStrokeCapRound: false,
              dotData: const FlDotData(show: false),
              aboveBarData: BarAreaData(
                  show: true,
                  cutOffY: 0,
                  gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colours.redF53F43.withOpacity(0.3),
                        Colours.main.withOpacity(0)
                      ]),
                  applyCutOffY: true),
              belowBarData: BarAreaData(
                  show: true,
                  cutOffY: 0,
                  gradient: LinearGradient(
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                      colors: [
                        Colours.blue2766D6.withOpacity(0.3),
                        Colours.blue2766D6.withOpacity(0)
                      ]),
                  // color: Colors.grey.withOpacity(0.3),
                  applyCutOffY: true))
        ],
        titlesData: FlTitlesData(
            show: true,
            rightTitles: AxisTitles(
                sideTitles: SideTitles(
              showTitles: true,
              // reservedSize: 20,
              interval: max == 0 ? null : max,
              getTitlesWidget: (value, meta) {
                final text = value.abs().toStringAsFixed(0);
                return QsText(
                  text,
                  textAlign: TextAlign.end,
                  fontSize: 12,
                  color: Colours.grey99,
                );
              },
            )),
            bottomTitles: AxisTitles(
                sideTitles: SideTitles(
              interval: ((logic.trends?.appMatchTrends?.isEmpty ?? true)
                          ? 0
                          : (logic.trends?.appMatchTrends!.first.per ?? 0) ??
                              0) >
                      0
                  ? perTime.toDouble()
                  : 1,
              showTitles: true,
              getTitlesWidget: (value, meta) {
                final text = (value == maxX && value > 0)
                    ? "FT"
                    : value.toStringAsFixed(0);
                return QsText(
                  text,
                  fontSize: 12,
                  color: Colours.grey99,
                );
              },
            )),
            leftTitles:
                const AxisTitles(sideTitles: SideTitles(showTitles: false)),
            topTitles:
                const AxisTitles(sideTitles: SideTitles(showTitles: false)))));
    return Stack(
      children: [
        Positioned.fill(
            child: Container(
          child: Row(
            children: [
              Expanded(child: Container(color: Colours.greyF7)),
              Expanded(child: Container(color: Colours.greyFB)),
              Expanded(child: Container(color: Colours.greyF7)),
              Expanded(child: Container(color: Colours.greyFB)),
            ],
          ).marginOnly(right: 20, bottom: 23),
        )),
        chart
      ],
    );
  }

  List<FlSpot> chartsData() {
    final trendsl = logic.trends?.appMatchTrends ?? [];
    if (trendsl.isEmpty) {
      return [];
    }
    final trends = trendsl.first;
    final data = trends.data ?? "";
    final per = trends.per ?? 0;
    final List<FlSpot> list = [FlSpot.zero];
    try {
      List l = jsonDecode(data);
      for (var i = 0; i < l.length; i++) {
        List l1 = l[i];
        for (var j = 0; j < per; j++) {
          final idx = i * per + j + 1;
          if (j < l1.length) {
            int num = l1[j];
            list.add(FlSpot(idx.toDouble(), -num.toDouble()));
          } else {
            list.add(FlSpot.nullSpot);
          }
        }
      }
    } catch (err) {
      log("$err");
    }
    return list;
  }

  Widget compareScoreCol(String s1, int? n1, int? n2,
      {double width = 80, Alignment alignment = Alignment.centerLeft}) {
    final c1 = (n1 ?? 0) >= (n2 ?? 0) ? Colours.text : Colours.grey99;
    final c2 = (n1 ?? 0) <= (n2 ?? 0) ? Colours.text : Colours.grey99;
    return scoreCol(s1, n1 == null ? "-" : "$n1", n2 == null ? "-" : "$n2",
        alignment: alignment,
        width: width,
        color1: c1,
        color2: c2,
        w1: FontWeight.w500);
  }

  Widget scoreCard(String text1, String text2, {int type = 0}) {
    final color = type == 1 ? const Color(0xFFF2F6FC) : const Color(0xFFFFF6F5);
    final borderColor =
        type == 1 ? const Color(0xFFCCE0FF) : const Color(0xFFFCCFCA);
    return Expanded(
      child: Container(
        height: 60,
        decoration: BoxDecoration(
            color: color,
            border: Border.all(color: borderColor, width: 0.5),
            borderRadius: BorderRadius.circular(4)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            QsText(
              text1,
              fontSize: 12,
              color: Color(0xff444444),
            ),
            const SizedBox(
              height: 4,
            ),
            QsText(text2, fontSize: 12),
          ],
        ),
      ),
    );
  }

  List<Widget> scoreScrollChildren(BoxConstraints p1) {
    List<Widget> children = [];

    var scores = logic.trends?.scoreArray() ?? [];

    final fixScores = (logic.trends?.periodCount == 2)
        ? const [BbScoreItem("上半场"), BbScoreItem("下半场")]
        : const [
            BbScoreItem("一"),
            BbScoreItem("二"),
            BbScoreItem("三"),
            BbScoreItem("四")
          ];

    for (var i = scores.length; i < (logic.trends?.periodCount ?? 0); i++) {
      scores.add(fixScores[i]);
    }

    final w =
        (logic.trends?.periodCount == 2) ? p1.maxWidth / 2 : p1.maxWidth / 4.5;
    children = scores
        .map((e) => compareScoreCol(e.name, e.away, e.home,
            width: w, alignment: Alignment.center))
        .toList();

    var fixWidth = p1.maxWidth - w * children.length;
    fixWidth = fixWidth > 0 ? fixWidth : 0;
    if (fixWidth > 0) {
      children.add(scoreCol("", "", "", width: fixWidth / 2));
      children.insert(0, scoreCol("", "", "", width: fixWidth / 2));
    }

    return children;
  }

  Widget score1234() {
    final score = logic.trends?.appMatchScore;
    return Container(
      margin: const EdgeInsets.only(left: 8, right: 8, bottom: 10),
      padding: const EdgeInsets.only(left: 12, right: 12, bottom: 12),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(8)),
      child: Column(
        children: [
          Row(
            children: [
              Image.asset(width: 24, Utils.getImgPath("match_stat_bars.png")),
              Container(width: 2),
              Container(
                alignment: Alignment.centerLeft,
                child:
                    QsText("每节比分", fontSize: 15, fontWeight: FontWeight.w500),
              ),
            ],
          ).paddingOnly(top: 16, bottom: 7),
          Row(
            children: [
              scoreCol("球队", logic.trends?.awayTeamName ?? "",
                  logic.trends?.homeTeamName ?? ""),
              Expanded(child: LayoutBuilder(builder: (context, p1) {
                log("max width = ${p1.maxWidth} maxheight = ${p1.maxHeight}");
                return SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  physics: const ClampingScrollPhysics(),
                  child: Row(
                    children: scoreScrollChildren(p1),
                  ),
                );
              })),
              compareScoreCol("总分", int.tryParse(score?.awayScore ?? ""),
                  int.tryParse(score?.homeScore ?? ""),
                  width: 50, alignment: Alignment.center),
            ],
          ),
          if ((logic.trends?.statusId ?? 0) < 10)
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                scoreCard(
                    "剩余暂停 ${score?.awayTimeOut}", "本节犯规 ${score?.awayFoul}"),
                const SizedBox(width: 11),
                scoreCard(
                    "剩余暂停 ${score?.homeTimeOut}", "本节犯规 ${score?.homeFoul}",
                    type: 1)
              ],
            ).marginSymmetric(vertical: 8)
        ],
      ),
    );
  }

  Widget scoreCol(String s1, String s2, String s3,
      {double width = 100,
      Alignment alignment = Alignment.centerLeft,
      Color? color1,
      Color? color2,
      FontWeight? w1}) {
    return Container(
      width: width,
      alignment: Alignment.centerLeft,
      child: Column(
        // crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Container(
              height: 30,
              alignment: alignment,
              child: QsText(s1, maxLines: 1, fontSize: 12)),
          const Divider(height: 0.5, color: Colours.greyEE),
          Container(
              height: 30,
              alignment: alignment,
              child: QsText(s2,
                  maxLines: 1,
                  fontWeight: w1,
                  fontFamily: "Din",
                  color: color1 ?? Colours.text)),
          const Divider(height: 0.5, color: Colours.greyEE),
          Container(
              height: 30,
              alignment: alignment,
              child: QsText(s3,
                  maxLines: 1,
                  fontWeight: w1,
                  fontFamily: "Din",
                  color: color2 ?? Colours.text))
        ],
      ),
    );
  }

  Widget techLineString(String name,
      {required String left,
      required String right,
      double leftPer = 0.0,
      double rightPer = 0.0,
      bool leftHighlight = false,
      bool rightHighlight = false}) {
    const blue = Colours.blue2766D6;
    const red = Colours.main;
    const grey = Colours.greyD7;
    const bg = Colours.greyF7;
    return SizedBox(
      height: 42,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              QsText(left,
                  fontSize: 16,
                  fontFamily: "din",
                  fontWeight: FontWeight.w300,
                  color: leftHighlight ? Colours.text : Colours.grey99),
              QsText(name, fontSize: 12),
              QsText(
                right,
                fontSize: 16,
                fontFamily: "din",
                fontWeight: FontWeight.w300,
                color: rightHighlight ? Colours.text : Colours.grey99,
              )
            ],
          ),
          const SizedBox(
            height: 2,
          ),
          Container(
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(2)),
            clipBehavior: Clip.hardEdge,
            child: Row(
              children: [
                Expanded(
                    child: Transform.rotate(
                        angle: math.pi,
                        child: myLinearProgress(
                          color: leftHighlight ? blue : grey,
                          minHeight: 6,
                          backgroundColor: bg,
                          value: leftPer,
                        ))),
                Expanded(
                    child: myLinearProgress(
                  minHeight: 6,
                  backgroundColor: bg,
                  color: rightHighlight ? red : grey,
                  value: rightPer,
                )),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget techLine(String name,
      {int left = 0, int right = 0, String? leftDesc, String? rightDesc}) {
    left = left >= 0 ? left : 0;
    right = right >= 0 ? right : 0;
    final total = left + right;
    final isLeft = left >= right;
    final isRight = right >= left;
    double leftPer = total == 0 ? 0 : left / total;
    double rightPer = total == 0 ? 0 : right / total;
    return techLineString(name,
        left: "$leftDesc",
        right: "$rightDesc",
        leftHighlight: isLeft,
        rightHighlight: isRight,
        leftPer: leftPer,
        rightPer: rightPer);
  }

  Widget myLinearProgress(
      {required double minHeight,
      required Color backgroundColor,
      required Color color,
      required double value}) {
    return LayoutBuilder(builder: (context, p1) {
      return Container(
        width: p1.maxWidth,
        height: minHeight,
        decoration: BoxDecoration(
            color: backgroundColor,
            borderRadius: const BorderRadius.only(
                topRight: Radius.circular(2), bottomRight: Radius.circular(2))),
        alignment: Alignment.centerLeft,
        child: Container(
          width: p1.maxWidth * value,
          decoration: BoxDecoration(
              color: color,
              borderRadius: const BorderRadius.only(
                  topRight: Radius.circular(2),
                  bottomRight: Radius.circular(2))),
        ),
      );
    });
  }

  Widget techBox() {
    final techsItems = logic.trends?.appMatchItems ?? [];
    double height = 313;
    final techs = [
      ...techsItems.map((e) => techLine(e.name ?? "",
          left: int.tryParse(e.away ?? "0") ?? 0,
          right: int.tryParse(e.home ?? "0") ?? 0,
          leftDesc: e.awayVis,
          rightDesc: e.homeVis))
    ];
    if (logic.showMore) {
      height = techs.length * 42 + 24 + 40 + 44;
    }

    return techs.isEmpty
        ? Container()
        : AnimatedContainer(
            margin: const EdgeInsets.only(left: 8, right: 8, bottom: 8),
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(8)),
            duration: const Duration(milliseconds: 200),
            height: height,
            clipBehavior: Clip.hardEdge,
            child: Column(
              children: [
                Expanded(
                    child: ListView(
                  physics: const NeverScrollableScrollPhysics(),
                  shrinkWrap: logic.showMore,
                  children: [
                    Row(
                      children: [
                        CachedNetworkImage(
                            width: 32,
                            height: 32,
                            imageUrl: logic.detail.detail?.awayTeamLogo ?? "",
                            placeholder: (context, url) =>
                                Styles.placeholderIcon(),
                            errorWidget: (context, url, error) => Image.asset(
                                Utils.getImgPath('lq_placeholder.png'))),
                        const SizedBox(width: 4),
                        QsText(logic.trends?.awayTeamName ?? ""),
                        const Spacer(),
                        QsText(logic.trends?.homeTeamName ?? ""),
                        const SizedBox(width: 4),
                        CachedNetworkImage(
                            width: 32,
                            height: 32,
                            imageUrl: logic.detail.detail?.homeTeamLogo ?? "",
                            placeholder: (context, url) =>
                                Styles.placeholderIcon(),
                            errorWidget: (context, url, error) => Image.asset(
                                Utils.getImgPath('lq_placeholder.png')))
                      ],
                    ).sized(height: 40),
                    ...techs
                  ],
                )),
                Container(
                  padding: const EdgeInsets.only(top: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      QsText(logic.showMore ? "收起数据" : "更多数据",
                          color: Colours.main, fontSize: 12),
                      Icon(
                        logic.showMore
                            ? Icons.keyboard_arrow_up_rounded
                            : Icons.keyboard_arrow_down_rounded,
                        color: Colours.main,
                      )
                    ],
                  ),
                ).tap(() => logic.showMore = !logic.showMore)
              ],
            ),
          );
  }
}
